/*
 * lora.c
 *
 *  Created on: 2019��4��26��
 *      Author: Administrator
 */
#include "stm32f0xx_hal.h"
#include "rf.h"
#include "spi.h"

/* spi send and read a byte*/
uint8_t SPI_ExchangeByte(uint8_t input)
{
    uint8_t spi1_rxData = 0;
    uint8_t spi1_txData = input;
    HAL_SPI_TransmitReceive(&hspi1, &spi1_txData, &spi1_rxData, 1, 200);

    return spi1_rxData;
}



void DelayMs(int8_t x)
{
    HAL_Delay(x);
}

void lora_send_data(void)
{
    uint8_t Sendbuffer[10] = {'1', '3', '4', '5', '6', '4', '2', '4', '9', 0};
    SX1276_SendPacket(Sendbuffer, 8);
    printf("%s\r\n", __FUNCTION__);
}

void lora_recv_data(void)
{
    uint8_t recv_buffer[65] = { 0 }, length = 0;;
    length = SX1276_ReceivePacket(recv_buffer);     // ����Ƿ��յ�һ�����ݰ�
    if(length != 0) 
    {
        printf("length = %d    data = %s \r\n", length, recv_buffer);
        SX1276_SetRxMode();    //必须的，暂时不清楚s
    }
}


void readSx1278reg(void)
{
    for(uint16_t addr_reg = 0x00; addr_reg <= 0x64; addr_reg++)
    {
        printf("Reg:0x%x  Val:0x%x \r\n", addr_reg, SX1276_ReadReg(addr_reg));
    }
}


void sx1278_lora_init(void)
{
    printf("sx1278 init\r\n");
    SX1276_Init(MODE_LORA);         		//SX127X ģ�鸴λ����ʼ��ΪLoRaģʽ
    SX1276_SetFreq(23);									//�����ŵ�Ϊ23����433MHz
    SX1276_LoRa_SetDataRate(2);
    SX1276_SetPower(15, 1);         		//����RFO PIN���������20dBm
    SX1276_SetRxMode(); 								// �������ģʽ
    readSx1278reg();
}

void lora_tester(void)
{
#if 0
    lora_send_data();
    HAL_Delay(1000);
#endif
    
#if 0
    printf("RegIrqFlags:0x%x\r\n", SX1276_ReadReg(REG_LR_IRQFLAGS));
    printf("RegRxNbBytes:0x%x\r\n", SX1276_ReadReg(REG_LR_NBRXBYTES));
//  HAL_Delay(1000);
    
#endif
    lora_recv_data();
}